// 根据环境加载对应的配置文件
const env = process.env.NODE_ENV || 'development';
require('dotenv').config({ path: `.env.${env}` });

const mysql = require("mysql2");

// 从环境变量获取配置，如果没有则使用默认值
const config = {
  host: process.env.DB_HOST,
  user: process.env.DB_USER,
  password: process.env.DB_PASSWORD,
  port: parseInt(process.env.DB_PORT),
  database: process.env.DB_NAME,
  charset: "utf8mb4",
  connectTimeout: parseInt(process.env.DB_CONNECT_TIMEOUT) || 10000,
  acquireTimeout: parseInt(process.env.DB_ACQUIRE_TIMEOUT) || 10000,
  timeout: parseInt(process.env.DB_TIMEOUT) || 10000,
  multipleStatements: false,
  // 连接池配置
  connectionLimit: parseInt(process.env.DB_CONNECTION_LIMIT) || 10,
  queueLimit: parseInt(process.env.DB_QUEUE_LIMIT) || 0,
  waitForConnections: true
};

// 使用连接池替代单个连接
const pool = mysql.createPool(config);

// 获取连接的Promise版本
const getConnection = () => {
  return pool.promise();
};

// 测试连接
const testConnection = async () => {
  try {
    const connection = await getConnection();
    await connection.execute('SELECT 1');
    console.log(`数据库连接池创建成功 (${env}环境)`);
    console.log(`连接配置: ${config.host}:${config.port}/${config.database}`);
    return true;
  } catch (error) {
    console.error("数据库连接失败:", error);
    return false;
  }
};

// 初始化连接
testConnection();

// 连接池事件监听
pool.on('connection', (connection) => {
  console.log('新的数据库连接已创建');
});

pool.on('error', (err) => {
  console.error('数据库连接池错误:', err);
});

pool.on('acquire', (connection) => {
  console.log('连接已从连接池获取');
});

pool.on('release', (connection) => {
  console.log('连接已释放回连接池');
});

// 优雅关闭
process.on('SIGINT', () => {
  console.log('正在关闭数据库连接池...');
  pool.end((err) => {
    if (err) {
      console.error('关闭连接池时出错:', err);
    } else {
      console.log('数据库连接池已关闭');
    }
    process.exit(0);
  });
});

module.exports = pool;